package com.util.httpUtil;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: tangs
 * @Date: 2019/6/21 10:17
 * @Description:
 */
public class HttpUtils {
    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 通用调用外部接口
     *
     * @param url
     * @param param
     * @return
     */
    public static Map doPostForData(String url, Map<String, Object> param) {
        logger.info("Http请求doPostForData url:" + url + " param:" + JSON.toJSONString(param));
        Map map = new HashMap();
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // 设置建立连接超时时间
            requestFactory.setConnectTimeout(10000);
            // 设置等待返回超时时间
            requestFactory.setReadTimeout(20000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            HttpHeaders httpheader = new HttpHeaders();
            httpheader.setContentType(MediaType.APPLICATION_JSON);
            httpheader.set("Authorization", (String) param.get("Authorization"));
            httpheader.set("Charset", "UTF-8");
            httpheader.set("Accept-Charset", "utf-8");
            HttpEntity httpEntity = new HttpEntity<>(param, httpheader);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            String result = responseEntity.getBody();
            map = JSON.parseObject(result, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("Http请求返回doPostForData result:" + JSON.toJSONString(map));
        return map;
    }

    /**
     * --get方式
     *
     * @param ssurl
     * @return
     */
    public static String doGetForData(String ssurl) throws Exception {

        URL url = new URL(ssurl);
        URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(20000).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        CloseableHttpResponse response = null;
        HttpGet httpGet = new HttpGet(uri);

        String result = null;
        try {
            response = httpClient.execute(httpGet);
            org.apache.http.HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPostForDataForGf(String url, Map<String, Object> param) {
        logger.info("Http请求doPostForData url:" + url + " param:" + JSON.toJSONString(param));
        String result = "";
        try {
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // 设置建立连接超时时间
            requestFactory.setConnectTimeout(10000);
            // 设置等待返回超时时间
            requestFactory.setReadTimeout(20000);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            HttpHeaders httpheader = new HttpHeaders();
            httpheader.setContentType(MediaType.APPLICATION_JSON);
            httpheader.set("accessToken", param.get("accessToken").toString());
            HttpEntity httpEntity = new HttpEntity<>(param, httpheader);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            result = responseEntity.getBody();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        logger.info("Http请求返回doPostForData result:" + JSON.toJSONString(result));
        return result;
    }

    /**
     * post
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String, Object> param) {
        try {
            RestTemplate restTemplate = getRestTemplate();
            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            HttpHeaders httpheader = new HttpHeaders();
            if (param.get("accessToken") != null) {
                httpheader.set("accessToken", param.get("accessToken").toString());
            }
            httpheader.setContentType(MediaType.APPLICATION_JSON);

            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,
                    new HttpEntity<Map<String, Object>>(param, httpheader), String.class);
            if (responseEntity != null && responseEntity.getBody() != null) {
                String result = responseEntity.getBody();
                logger.info(result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置超时时间
     *
     * @return
     */
    public static RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(60000);// 设置建立连接超时时间
        requestFactory.setReadTimeout(60000);// 设置等待返回超时时间
        return new RestTemplate(requestFactory);
    }
}
